package 单周赛.september;

import java.util.*;

/**
 * @
 * @date 2024/06/30
 */
public class 第404场单周赛 {

    public static void main(String[] args) {

        第404场单周赛 impl = new 第404场单周赛();

        System.out.println(impl.maximumLength(new int[]{1, 5, 9, 2, 8}, 2));

        System.out.println(impl.minimumDiameterAfterMerge(new int[][]{{0, 1}, {0, 2}, {0, 3}, {2, 4}, {2, 5}, {3, 6}, {2, 7}},
                new int[][]{{0, 1}, {0, 2}, {0, 3}, {2, 4}, {2, 5}, {3, 6}, {2, 7}}));

    }

    /**
     * 动态规划
     */
    public int maximumLength(int[] nums, int k) {
        Map<Integer, Integer>[] dp = new HashMap[nums.length];
        for (int i = 0; i < nums.length; i++) {
            dp[i] = new HashMap();
        }

        int max = 0;

        for (int i = 1; i < nums.length; i++) {
            for (int j = 0; j < i; j++) {
                int mod = (nums[j] + nums[i]) % k;

                dp[i].put(mod, Math.max(dp[i].getOrDefault(mod, 0), dp[j].getOrDefault(mod, 0) + 1));

                max = Math.max(max, dp[i].get(mod));
            }
        }

        return max + 1;
    }

    /**
     * 数的直径是任意两个节点的最大路径
     * 1，假设两棵树的直径都是 5 ，发现在中间相连，可以使得合并之后的树最大直径最小
     * * |   |
     * * |   |
     * * | _ |
     * * |   |
     * * |   |
     * * |   |
     * 2，另外一种情况是某棵树的直径非常大，直接取最大的直径
     * 3，Floyd多源最短路（超出内存限制）
     */
    public int minimumDiameterAfterMerge(int[][] edges1, int[][] edges2) {

        int dis1 = findTheCity(edges1.length - 1, edges1);
        int dis2 = findTheCity(edges2.length - 1, edges2);
        return Math.max(Math.max(dis1, dis2), (dis1 + 1) / 2 + (dis2 + 1) / 2 + 1);
    }

    public int findTheCity(int n, int[][] edges) {
        int[][] w = new int[n][n];
        for (int[] row : w) {
            Arrays.fill(row, Integer.MAX_VALUE / 2); // 防止加法溢出
        }
        for (int[] e : edges) {
            int x = e[0], y = e[1], wt = 1;
            w[x][y] = w[y][x] = wt;
        }

        int ans = 0;
        int[][] f = w;
        for (int k = 0; k < n; k++) {
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < n; j++) {
                    if (i == j) continue;
                    f[i][j] = Math.min(f[i][j], f[i][k] + f[k][j]);

                    if (f[i][j] < Integer.MAX_VALUE / 2) {
                        ans = Math.max(ans, f[i][j]);
                    }
                }
            }
        }

        return ans;
    }

}
